﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Meraz.Core.Model;
using Meraz.Core.Repositories;

namespace Meraz.Core.Commands
{
    public interface IAddTwitterUserCommand : ICommand<TwitterUser>
    {
        int StudyID { get; set; }
        string UserName { get; set; }
        ITwitterStudyRepository TwitterStudyRepository { get; set; }
        ITwitterUserRepository TwitterUserRepository { get; set; }
    }
    public class AddTwitterUserCommand : BaseCommand, IAddTwitterUserCommand
    {
        public int StudyID { get; set; }
        public string UserName { get; set; }
        public TwitterUser Result { get; set; }
        public ITwitterStudyRepository TwitterStudyRepository { get; set; }
        public ITwitterUserRepository TwitterUserRepository { get; set; }
        public AddTwitterUserCommand(ITwitterStudyRepository twitterStudyRepository, ITwitterUserRepository twitterUserRepository)
        {
            TwitterStudyRepository = twitterStudyRepository ?? new TwitterStudyRepository();
            TwitterUserRepository = twitterUserRepository ?? new TwitterUserRepository();
        }

        public void Execute()
        {
            if (StudyID <= 0)
                throw new ApplicationException("Missing StudyID");
            if (string.IsNullOrWhiteSpace(UserName))
                throw new ApplicationException("Missing UserName");

            TwitterUser user = TwitterUserRepository.GetByUsername(UserName);
            if (user == null)
                throw new ApplicationException("Invalid UserName");

            TwitterStudy study = TwitterStudyRepository.GetById(StudyID);
            if (study == null)
                throw new ApplicationException("Invalid StudyID");

            if (study.TwitterUsers == null)
                study.TwitterUsers = new List<TwitterUser>();
            if (!study.TwitterUsers.Contains(user))
            {
                study.TwitterUsers.Add(user);
                //user.TwitterStudies.Add(study);
                Commit();
            }
            Result = user;
        }
    }
}
